<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
//创建异步对象
function createXMLHttpRequest(){
	try {
		return new XMLHttpRequest();//非IE浏览器
	} catch (e) {
			try {
				return new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
					try {
						return new ActiveXObject("Microsoft.XMLHTTP");
					} catch (e) {
						alert("你用的什么浏览器！");
						throw e;
					}
			}
	}
}
window.onload = function(){
	//获取文本框，给失去焦点事件添加监听
	var username = document.getElementById("usernameEle");
	username.onblur = function(){
		//1、得到异步对象
		var xmlHttp = createXMLHttpRequest();
		//2、打开连接
		xmlHttp.open("POST","<c:url value='/ValidateUsernameServlet'/>",true);
		//3、设置请求头
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		//4、发送请求
		xmlHttp.send("username="+username.value);
		//5、给xmlHttp的onreadystatechange事件注册监听
		xmlHttp.onreadystatechange = function(){
			if(xmlHttp.readyState == 4 && xmlHttp.status == 200){//双重判断
				//获取服务器的响应，判断是否为1
				//是的话，获取span，添加内容“用户名已创建”
				var text = xmlHttp.responseText;
				var span = document.getElementById("errorSpan");//获取span元素
				if(text == "1"){//判断是否为
					span.innerHTML="用户名已创建！";	
				}else{
					span.innerHTML="";
				}
			}
		};
	};
};
</script>
<style type="text/css">
	Span{
		color:red;
	}
</style>
</head>
<body>
	<h1>演示用户名是否被注册</h1>
	<form action="" method="post" >
		用户名：<input type="text" name="username" id="usernameEle"/><span id="errorSpan"></span><br>
		密&nbsp;&nbsp;&nbsp;&nbsp;码：<input type="password" name="pwd"/><br>
		<input type="submit" value="注册"/>
	</form>
</body>
</html>